package com.tengxing.e1.FactoryTest;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.maiarstar.e101.protocol.cerebellum.api.exception.ProtocolException;
import com.maiarstar.e101.protocol.cerebellum.api.model.SADAInfo;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolGetter;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolSetter;
import com.maiarstar.e101.protocol.cerebellum.sdk.CerebellumProtocolSdkManager;

public class SADA_Test_Activity extends AppCompatActivity {
    private static final String TAG = "SADA_Test_Activity";
    private CerebellumProtocolSdkManager cerebellumProtocolSdkManager;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    Button btn_SADA_Pass, btn_SADA_Fail, btn_SADA_Get, btn_SADA_Reset, btn_SADA_Set;
    TextView tV_SADA1_Set, tV_SADA2_Set;
    SeekBar seekBar_SADA1, seekBar_SADA2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sada_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        sharedPreferences = getSharedPreferences("Test_Result", MODE_PRIVATE);
        initCerebellumManager();
        tV_SADA1_Set = findViewById(R.id.tV_SADA1_Set);
        tV_SADA2_Set = findViewById(R.id.tV_SADA2_Set);
        seekBar_SADA1 = findViewById(R.id.seekBar_SADA1);
        seekBar_SADA2 = findViewById(R.id.seekBar_SADA2);
        Factory_SADA_SB(1, seekBar_SADA1, tV_SADA1_Set);
        Factory_SADA_SB(2, seekBar_SADA2, tV_SADA2_Set);
        Factory_SADA_BTN();
    }
    private void initCerebellumManager() {
        CerebellumProtocolSdkManager sdkProtocolManager = new CerebellumProtocolSdkManager(this);
        CerebellumProtocolSdkManager.SdkParams sdkParams = CerebellumProtocolSdkManager.getDeafultSdkParams();
        try {
            sdkProtocolManager.init(sdkParams);
        } catch (ProtocolException e) {
            Log.w(TAG, e.getMessage());
        }
        this.cerebellumProtocolSdkManager = sdkProtocolManager;
    }

    private void Factory_SADA_SB(int num, SeekBar seekBar, TextView textView){
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int degree = 0;
            String textView_str = "舵机"+num+"设定角度：";
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                switch (progress){
                    case 1:{
                        degree = 0;
                        break;
                    }
                    case 2:{
                        degree = 45;
                        break;
                    }
                    case 3: {
                        degree = 90;
                        break;
                    }
                    case 4: {
                        degree = 135;
                        break;
                    }
                    case 5: {
                        degree = 180;
                        break;
                    }
                    default:
                        break;
                }
                textView_str = "舵机"+num+"设定角度："+degree+"°";
                textView.setText(textView_str);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(SetSADA(num, degree)){
                    Toast.makeText(SADA_Test_Activity.this, textView_str+"设定成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(SADA_Test_Activity.this, textView_str+"设定失败", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
    private void Factory_SADA_BTN(){
        btn_SADA_Pass = findViewById(R.id.btn_SADA_Pass);
        btn_SADA_Pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("SADA","通过");
                if(editor.commit()){
                    Toast.makeText(SADA_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(SADA_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(SADA_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_SADA_Fail = findViewById(R.id.btn_SADA_Fail);
        btn_SADA_Fail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("SADA","未通过");
                if(editor.commit()){
                    Toast.makeText(SADA_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(SADA_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(SADA_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_SADA_Get = findViewById(R.id.btn_SADA_Get);
        btn_SADA_Get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Refresh_SADA_Status(btn_SADA_Get)){
                    Toast.makeText(SADA_Test_Activity.this, "刷新成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(SADA_Test_Activity.this, "刷新失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_SADA_Reset = findViewById(R.id.btn_SADA_Reset);
        btn_SADA_Reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean reset_status = SetSADA(1, 90);
                if(!SetSADA(2, 90)){
                    reset_status = false;
                }
                if(reset_status){
                    Toast.makeText(SADA_Test_Activity.this, "复位成功", Toast.LENGTH_SHORT).show();
                    seekBar_SADA1.setProgress(3);
                    seekBar_SADA2.setProgress(3);
                    tV_SADA1_Set.setText("舵机1设定角度：90°");
                    tV_SADA2_Set.setText("舵机2设定角度：90°");
                }else{
                    Toast.makeText(SADA_Test_Activity.this, "复位失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_SADA_Set = findViewById(R.id.btn_SADA_Set);
        btn_SADA_Set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean reset_status = SetSADA(1, 180);
                if(!SetSADA(2, 180)){
                    reset_status = false;
                }
                if(reset_status){
                    Toast.makeText(SADA_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                    seekBar_SADA1.setProgress(5);
                    seekBar_SADA2.setProgress(5);
                    tV_SADA1_Set.setText("舵机1设定角度：180°");
                    tV_SADA2_Set.setText("舵机2设定角度：180°");
                }else{
                    Toast.makeText(SADA_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private boolean Refresh_SADA_Status(Button btn){
        String sada_info_str = "刷新舵机当前状态：";
        boolean ret = true;
        int angle = -1;
        for(int i=1; i<3 ; i++){
            angle = GetSADA(i);
            if(angle == -1){
                sada_info_str = sada_info_str.concat("舵机"+i+"：获取失败  ");
                ret = false;
                Toast.makeText(SADA_Test_Activity.this, "刷新成功", Toast.LENGTH_SHORT).show();
            }else{
                sada_info_str = sada_info_str.concat("舵机"+i+"："+angle+"°  ");
            }
        }
        if(GetSADAOnLine(1) == 0x31){
            sada_info_str = sada_info_str.concat("舵机在位");
        } else if (GetSADAOnLine(1) == 0x30) {
            sada_info_str = sada_info_str.concat("舵机不在位");
        }else{
            sada_info_str = sada_info_str.concat("舵机在位信息错误");
        }
        btn.setText(sada_info_str);
        return ret;
    }

    private int GetSADA(int num) throws ProtocolException {
        try {
            ICerebellumProtocolGetter getter = this.cerebellumProtocolSdkManager.getCerebellumProtocolGetter();
            return getter.getSADAInfo(num).getCurrent_angle();
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return -1;
    }

    private int GetSADAOnLine(int num) throws ProtocolException {
        try {
            ICerebellumProtocolGetter getter = this.cerebellumProtocolSdkManager.getCerebellumProtocolGetter();
            return getter.getSADAInfo(num).getReign();
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return -1;
    }

    private boolean SetSADA(int num, int degree) throws ProtocolException {
        try {
            SADAInfo sadaInfo = new SADAInfo();
            sadaInfo.setOrder(num);
            sadaInfo.setCurrent_angle(degree);
            ICerebellumProtocolSetter setter = this.cerebellumProtocolSdkManager.getCerebellumProtocolSetter();
            return setter.setSADAInfo(sadaInfo);
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }



    @Override
    public void onBackPressed() {
        Intent intent = new Intent(SADA_Test_Activity.this, MainActivity.class);
        startActivity(intent);
        finish();
        Toast.makeText(SADA_Test_Activity.this, "直接退出不会保存结果", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }

}